var net = require('net');
var log4js = require("log4js");
var config = require('./config.json');

log4js.configure(config);
const logger = log4js.getLogger('server');

exports.start = function (route) {

        var server = net.createServer();
        logger.info('Create tcp service successfully');

        server.on('connection', function(socket) {
            logger.info('got a new connection');
            socket.on('data', function(data) {
                logger.info('got a new request');
                logger.debug('request : ', data.toString());
                var ret = route(data.toString());

                if(ret) {
                    socket.write(ret);
                }
                logger.debug('response : ', ret);
            });
            socket.on('close', function() {
                logger.info('connection closed');
            });
            // socket.on('end', function() {
            //     logger.info('connection end');
            // });
            socket.on('error', function(err) {
                logger.info('client error:', err.message);
            });
        });

        var shutdown = function () {
            server.close();
        };

        process.on('SIGTERM', shutdown);
        process.on('SIGINT', shutdown);

        server.on('error', function(err) {
            logger.error('Server error: ', err.message);
            console.log('Server error: ' + err.message);
        });
        server.on('close', function() {
            logger.info('Server closed');
            console.log('Received the exit message, the program exits');
            process.exit();
        });
        server.on('listening', function() {
            logger.info("Server has started, listening on 127.0.0.1:%d", config.socket.lisentPort);
        });
        server.listen(config.socket.lisentPort);
};